﻿using System;
using System.Collections.Generic;
using System.Configuration;

namespace smp.QueryDb
{
    internal static class InstanceFactory
    {
        private static ILog _log;
        private static Dictionary<string, IDbAdapter> _adapters;
        
        static InstanceFactory()
        {
            _log = new DebugLog();
            _adapters = new Dictionary<string, IDbAdapter>();
            _adapters.Add("System.Data.SqlClient", new SqlAdapter());
            var showSqlSetting = ConfigurationManager.AppSettings["showsql"];
            if(!string.IsNullOrEmpty(showSqlSetting) && showSqlSetting.ToLower() == "true")
            {
                ShowSql = true;
            }
        }

        internal static ILog Log { get { return _log; } }

        internal static bool ShowSql { get; private set; }
        

        internal static void SetLog(ILog log)
        {
            _log = log;
        }

        internal static IDbAdapter GetAdapter(string providerName)
        {
            if (!_adapters.ContainsKey(providerName))
            {
                throw Helper.Error("IDbAdapter implementation not registered for provider name : {0}", providerName);
            }
            return _adapters[providerName];
        }

        internal static void RegisterAdapter(IDbAdapter adapter, string providerName)
        {
            if (_adapters.ContainsKey(providerName))
            {
                _adapters.Remove(providerName);
            }
            _adapters.Add(providerName, adapter);
        }
    }
}
